import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Vte', '3.91')
from gi.repository import Gtk, Vte, Gio, GLib

class TerminalWindow(Gtk.ApplicationWindow):
    def __init__(self, app):
        super().__init__(title="Terminal Example", default_width=800, default_height=600)
        self.set_application(app)
        
        # 创建一个Vte.Terminal实例
        self.terminal = Vte.Terminal()
        self.terminal.set_audible_bell(False)  # 关闭响铃
        self.terminal.set_scrollback_lines(1000)  # 设置滚动行数

        self.set_child(self.terminal)
        self.do_spawn_2()

    def do_spawn_1(self):
        self.terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT, 
            None, 
            ['/bin/bash'], 
            None, 
            GLib.SpawnFlags.DO_NOT_REAP_CHILD, 
            None, 
            None
        )

    def on_spawn_complete(self, terminal, res):
        pid, status = terminal.spawn_finish(res)
        if status:
            print("Failed to spawn terminal:", status)
        else:
            print("Terminal PID:", pid)

    def do_spawn_2(self):
        self.terminal.spawn_async(
            Vte.PtyFlags.DEFAULT,
            None,
            GLib.Variant('as', ['/bin/bash', '-c', 'bash']),
            GLib.Variant('a{sv}', {}),
            0,  # 使用0替代被禁用的标志
            None,
            None,
            -1,
            None,
            None
        )

class App(Gtk.Application):
    def __init__(self):
        super().__init__(application_id='com.example.terminal', flags=Gio.ApplicationFlags.DEFAULT_FLAGS)
        self.window = None
    
    def do_activate(self):
        if not self.window:
            self.window = TerminalWindow(self)
        self.window.present()

app = App()
app.run()

# terminal.grab_focus()
# terminal.fork_command_full(Vte.PtyFlags.DEFAULT, ['/usr/bin/ssh', 'user@hostname', 'command'], None, 0, None, None, None, None)

# https://yiyan.baidu.com
# https://chat.baidu.com